<template>
    <div class="app-container" v-loading="pageLoading">
        <!-- 搜索栏 -->
        <div class="flex flex-center flex-col-between">
            <div class="text-wrap">
                <div class="desc-text text-primary">
                    <i class="el-icon-s-grid" />
                    <span class="text">异常任务</span>
                </div>
                <el-radio-group v-model="radio" @change="radioCheck" class="ml-10 mt-5">
                    <el-radio-button :label="1">我创建</el-radio-button>
                    <el-radio-button :label="3">待处理</el-radio-button>
                    <el-radio-button :label="2">处理过</el-radio-button>
                </el-radio-group>
            </div>
            
            <div class="filter-container flex flex-row-sb">
                <el-input v-model="query.abnormalTaskCode" placeholder="请输入异常任务编码" clearable style="width: 150px"
                    class="mr-10" @keyup.enter="getList" />
                <el-select filterable v-model="query.priority" placeholder="请选择优先级" style="width: 150px" clearable class="mr-10">
                    <el-option filterable v-for="item in priorityList" :key="item.key" :label="item.value" 
                        :value="item.key" />
                </el-select>
                <el-cascader :options="treeData" v-model="query.abnormalTypeId" filterable class="mr-10"
                    :props="{ checkStrictly: true }" placeholder="请选择异常类型" clearable style="width: 150px" />
                <el-select filterable v-model="query.status" placeholder="请选择状态" style="width: 150px" clearable>
                    <el-option filterable v-for="item in statusOptions" :key="item.key" :label="item.value"
                        :value="item.key" />
                </el-select>
                <el-button class="ml-20" type="primary" plain @click="research">查询</el-button>
                <el-button type="success" plain class="fr" @click="createItem">创建</el-button>
            </div>
        </div>
        <!-- 表格 -->
        <z-table :list="list" :tableProps="tableProps" :columns="columns" v-loading="tableLoading">
            <template v-slot:content="{ row, key }">
                <span v-if="key === 'Status'" 
                :class="row[key]==5?'text-gray':row[key]==3?'text-red':row[key]==1||row[key]==2?'text-yellow':'text-green'">
                {{ formatStatus(row[key]) }}</span>
                <span v-else-if="key === 'AbnormalTypeId'">{{ formatType(row[key]) }}</span>
                <span v-else-if="key === 'Initiator'">{{ formatUser(row[key]) }}</span>
                <span v-else-if="key === 'Priority'">{{ formatPriority(row[key]) }}</span>
                <span v-else-if="key === 'LastProcessor'">{{ formatUser(row[key]) }}</span>
                <span v-else-if="key === 'CurrentProcessor'">{{ formatUser(row[key]) }}</span>
                <span v-else-if="key === 'EquipmentCodesNames'">{{ formatUser(row[key]).join(',') }}</span>
                <span v-else-if="key === 'InitiatorAttachmentImages'">
                    <div style="display: flex; flex-wrap: wrap;gap:10px">
                        <el-image v-for="(img, index) in row[key]" :preview-teleported="true" :key="index"
                            style="width: 60px; height: 60px;" :src="img.url"
                            :preview-src-list="row[key].map(t => { return t.url })"></el-image>
                    </div>
                </span>
                <span v-else-if="key === 'TreatmentAttachmentsImages'">
                    <div style="display: flex; flex-wrap: wrap;gap:10px">
                        <el-image v-for="(img, index) in row[key]" :preview-teleported="true" :key="index"
                            style="width: 60px; height: 60px;" :src="img.url"
                            :preview-src-list="row[key].map(t => { return t.url })"></el-image>
                    </div>
                </span>
                <span v-else>{{ row[key] }}</span>
            </template>
            <template v-slot:operation="v">
                <div class="inline-flex flex-row-sa" style="width: 300px">
                    <div v-if="(v.row.Status == 0 && formatUser(v.row.Initiator) == userinfo.userName) && radio != 2">
                        <a href="#" class="text-blue mr-5" @click.prevent="editItem(v.row)" v-if="!v.row.IsRead">编辑</a>
                        <a href="#" class="text-red mr-5" @click.prevent="delItem(v.row)" v-if="!v.row.IsRead">删除</a>
                    </div>
                    <div v-else>
                        <a href="#" class="text-green mr-5" @click.prevent="operationItem(v.row)">
                            {{ v.row.IsRead || v.row.Status == '5' ? '查看' : '操作' }}</a>
                    </div>
                </div>
            </template>
        </z-table>

        <!-- 分页 -->
        <z-pagination :pagination="pagination" :total="total" v-model:page="query.limit" v-model:limit="query.rows"
            @change="getList" />

        <abnormal-task-dialog ref="dialog" @save-success="getList" @success="getList" />

        <!-- 图片预览弹框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
            <div class="image-container">
                <img :src="dialogImageUrl" alt="预览图片" class="responsive-image" />
            </div>
        </el-dialog>
    </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import store from '@/store/index'
import AbnormalTaskDialog from './components/AbnormalTaskDialog.vue'
import _ from 'lodash'
import http from '@/../src/api/http.js'
const url = http.ipAddress
export default {
    mixins: [commonMixin],
    name: 'AdsAbnormalTask',
    components: {
        AbnormalTaskDialog,
    },
    data() {
        return {
            query: {
                priority:null,//优先级
                abnormalTaskCode: '', // 异常编码搜索
                abnormalTypeId: '', // 状态搜索
                status: '', //状态
                limit: 1,
                rows: 10,
            },
            radio: 3,//数据状态 1我创建、2处理过、3待处理
            userinfo: {}, //web用户信息
            list: [], // 表格数据
            total: 0, // 总条数
            pageLoading: false, // 页面加载状态
            tableLoading: false, // 表格加载状态
            // editFormVisible: false, // 编辑弹框显示状态
            formData: {}, // 表单数据
            submitLoading: false, // 表单提交加载状态
            addTreeData: [], //树状结构
            treeData: [], //树状结构
            treeList: [], //非树状结构
            Sys_UserList: [],
            APS_PostList: [],
            BASE_MachineList: [], //设备集合
            deptList: [],
            priorityList: [],//优先级
            statusOptions: [], // 状态选项
            dialogTitle: '',
            dialogVisible: false, //展示图片
            dialogImageUrl: '', //图片地址
            tableProps: {
                'scrollbar-always-on': true,
                border: true,
                opsColWith: 150,
                hideOperations: false,
                NOscrollBar: true,
                'highlight-current-row': true,
            },
            columns: [
                { title: '异常编码', key: 'TaskCode', width: 150 },
                { title: '异常类型', key: 'AbnormalTypeId', width: 150 },
                { title: '创建人', key: 'Initiator', width: 120 },
                { title: '设备', key: 'EquipmentCodesNames', width: 250 },
                { title: '状态', key: 'Status', width: 100 },
                { title: '优先度', key: 'Priority', width: 100 },
                { title: '异常说明', key: 'InitiatorRemarks', width: 200 },
                { title: '异常附件', key: 'InitiatorAttachmentImages', width: 240 },
                // { title: '当前处理人', key: 'CurrentProcessor', width: 120 },
                // { title: '最后处理人', key: 'LastProcessor', width: 120 },
                { title: '处理方法', key: 'TreatmentMethod', width: 120 },
                { title: '处理结果', key: 'TreatmentResult', width: 120 },
                { title: '处理附件', key: 'TreatmentAttachmentsImages', width: 240 },
                { title: '创建时间', key: 'CreateTime', width: 180 },
            ],
            fields: [
                { title: '异常编码', key: 'TaskCode', disabled: true },
                {
                    title: '异常类型',
                    key: 'AbnormalTypeId',
                    type: 'cascader', // 使用级联选择器
                    props: {
                        options: this.treeList, // 绑定 treeList 数据
                        checkStrictly: true, // 可以选择任意一级
                        clearable: true, // 可清空
                        placeholder: '请选择异常类型', // 占位符
                    },
                },
                { title: '发起人', key: 'Initiator' },
                { title: '发起备注', key: 'InitiatorRemarks', type: 'textarea' },
                {
                    title: '状态',
                    key: 'Status',
                    type: 'select',
                    options: this.statusOptions,
                },
            ],
            formProps: {
                labelWidth: '120px',
            },
        }
    },
    created() {
        this.userinfo = store.getters.getUserInfo()
        this.initData1()
            .then(() => {
                this.getList()
            })
            .catch((error) => {
                console.error('初始化数据失败:', error)
            })
    },
    methods: {
        radioCheck(e) {
            console.log(e)
            this.getList()
        },
        async initData1() {
            try {
                this.pageLoading = true
                // 使用 Promise.all 并行处理多个请求
                const [response1, response2, response3] = await Promise.all([
                    this.http.get('/api/Ads_AbnormalType/GetTree', null, {}),
                    this.http.get('/api/Ads_AbnormalType/GetTree', { isFilter: true }, {}),
                    this.http.post('api/Sys_Dictionary/GetVueDictionary', [
                        'Sys_User',
                        'APS_Post',
                        '部门级联',
                        'Ads_Abnormal_OperationStatus',
                        'BASE_Machine',
                        "Ads_Abnormal_Priority",
                    ]),
                ])

                // 异常树
                const flattenTree = (data) => {
                    const result = []
                    const traverse = (node) => {
                        result.push({
                            key: node.AbnormalTypeId,
                            value: node.AbnormalName,
                        })
                        if (node.Children && node.Children.length > 0) {
                            node.Children.forEach(traverse)
                        }
                    }
                    data.forEach(traverse)
                    return result
                }

                this.treeList = flattenTree(response1)
                this.treeData = this.transformTreeData(response1)

                // 异常树-过滤
                this.addTreeData = this.transformTreeData(response2)

                // 字典
                response3.forEach((t) => {
                    if (t.DictionaryNo == 'Sys_User') {
                        this.Sys_UserList = t.data
                    }
                    if (t.DictionaryNo == 'APS_Post') {
                        this.APS_PostList = t.data
                    }
                    if (t.DictionaryNo == '部门级联') {
                        this.deptList = t.data
                    }
                    if (t.DictionaryNo == 'Ads_Abnormal_OperationStatus') {
                        this.statusOptions = t.data
                    }
                    if (t.DictionaryNo == 'BASE_Machine') {
                        this.BASE_MachineList = t.data
                    }
                    if (t.DictionaryNo == 'Ads_Abnormal_Priority') {
                        this.priorityList = t.data
                    }
                })
            } catch (error) {
                this.pageLoading = false
                console.error('初始化数据失败:', error)
                throw error // 抛出错误以便外部捕获
            } finally {
                this.loading = false
            }
        },
        transformTreeData(items) {
            return items.map((item) => ({
                parentId: item.ParentId,
                value: item.AbnormalTypeId,
                label: `${item.AbnormalName}`,
                children: item.Children ? this.transformTreeData(item.Children) : [],
                rawData: item,
            }))
        },
        // 获取列表数据
        async getList() {
            const data = { ...this.query }
            data.DataType = this.radio
            if (this.query.abnormalTypeId !== undefined) {
                data.abnormalTypeId = data.abnormalTypeId[data.abnormalTypeId.length - 1]
            }
            this.tableLoading = true
            try {
                const res = await this.http.post('/api/Ads_Task/page', data)
                this.total = res.total
                this.list = res.abnormalTasks
                this.list.forEach((t) => {
                    // 初始附件
                    t.InitiatorAttachmentImages = t.InitiatorAttachments ? JSON.parse(t.InitiatorAttachments) : []
                    t.InitiatorAttachmentImages = this.addUrlPrefix(t.InitiatorAttachmentImages)

                    // 处理附件
                    t.TreatmentAttachmentsImages = t.TreatmentAttachments ? JSON.parse(t.TreatmentAttachments) : []
                    t.TreatmentAttachmentsImages = this.addUrlPrefix(t.TreatmentAttachmentsImages)

                    // 设备
                    t.EquipmentCodesNames = []
                    if (t.EquipmentCodes) {
                        t.EquipmentCodes = JSON.parse(t.EquipmentCodes)
                        t.EquipmentCodes.forEach((equipment) => {
                            const machine = this.BASE_MachineList.find((item) => item.key === equipment)
                            t.EquipmentCodesNames.push(machine ? machine.value : '未知设备')
                        })
                    }
                    //发起人
                })
            } catch (error) {
                console.error('获取数据失败:', error)
            } finally {
                this.tableLoading = false
                this.pageLoading = false
            }
        },

        // 格式化状态
        formatStatus(status) {
            var value = this.statusOptions.find((t) => t.key == status)
            return value ? value.value : status
        },
        formatUser(user) {
            var value = this.Sys_UserList.find((t) => t.key == user)
            return value ? value.value : user
        },
        formatPriority(Priority) {
            var value = this.priorityList.find((t) => t.key == Priority)
            return value ? value.value : Priority
        },
        formatType(typeId) {
            var value = this.treeList.find((t) => t.key == typeId)
            return value ? value.value : typeId
        },
        createItem(row) {
            var listData = {
                priorityList: this.priorityList,
                deptList: this.deptList,
                BASE_MachineList: this.BASE_MachineList, //设备
                treeData: this.addTreeData, //使用过滤后的节点
                userList: this.Sys_UserList,
                statusOptions: this.statusOptions,
            }
            this.$refs.dialog.openDialog(0, listData)
        },
        // 编辑任务
        editItem(row) {
            var listData = {
                priorityList: this.priorityList,
                deptList: this.deptList,
                BASE_MachineList: this.BASE_MachineList, //设备
                treeData: this.addTreeData, //使用过滤后的节点
                userList: this.Sys_UserList,
                statusOptions: this.statusOptions,
            }
            this.$refs.dialog.openDialog(1, listData, row)
        },
        operationItem(row) {
            var listData = {
                priorityList: this.priorityList,
                deptList: this.deptList,
                BASE_MachineList: this.BASE_MachineList, //设备
                treeData: this.treeData,
                userList: this.Sys_UserList,
                statusOptions: this.statusOptions,
            }
            this.$refs.dialog.openDialog(2, listData, row)
        },
        delItem(row) {
            this.$confirm('确定要删除该条数据吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.http
                        .post('/api/Ads_Task/del', [row.TaskId])
                        .then((r) => {
                            this.getList()
                        })
                        .catch((error) => { })
                })
                .catch(() => { })
        },
        addUrlPrefix(fileList) {
            if (fileList != null) {
                return fileList.map((file) => {
                    // 如果 aa 已经有前缀，避免重复添加
                    if (!file.url.startsWith(url)) {
                        file.url = url + file.url
                    }
                    return file
                })
            } else {
                return []
            }
        },
        handlePictureCardPreview(uploadFile) {
            console.log('jav', uploadFile)
            this.dialogImageUrl = uploadFile.url
            this.dialogVisible = true
            this.dialogTitle = uploadFile.name
        },
    },
}
</script>

<style lang="scss" scoped>
@import '../../../style/index.scss';

.text-wrap {
    height: 40px;
    position: relative;
    padding-bottom: 8px;
    display: flex;

    .desc-text {
        //  display: inline-block;
        margin-top: 7px;
        font-weight: bold;
        //margin-bottom: 3px;
        font-size: 14px;
        white-space: nowrap;
        border-bottom: 2px solid #7300e6;

        i {
            font-size: 16px;
            position: relative;
            top: 1px;
            margin-right: 2px;
        }
    }
}
</style>